package com.uchonor.api.core.template;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.uchonor.api.constant.ConstVal;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Freemarker 模板引擎实现文件输出
 */
public class FreemarkerTemplateEngine extends AbstractTemplateEngine {
    private Configuration configuration;

    @Override
    public AbstractTemplateEngine init() {
        configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding(ConstVal.UTF8);
        configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, StringPool.SLASH);
        return this;
    }

    @Override
    public String getTemplateStr(Map<String, Object> objectMap, String templatePath) throws IOException, TemplateException {
        Template template = configuration.getTemplate(templatePath);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        template.process(objectMap,new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8));
        return new String(byteArrayOutputStream.toByteArray(), "UTF-8");
    }
}
